#!/bin/bash

# VLESS 链接
VLESS_URL="$1"

if [ -z "$VLESS_URL" ]; then
  echo "Usage: $0 <vless://链接>"
  exit 1
fi

# 解析 URL
UUID=$(echo "$VLESS_URL" | sed -n 's|.*vless://\([^@]*\)@.*|\1|p')
ADDRESS=$(echo "$VLESS_URL" | sed -n 's|.*@\([^:]*\):.*|\1|p')
PORT=$(echo "$VLESS_URL" | sed -n 's|.*:\([0-9]*\)\?.*|\1|p')
ENCRYPTION=$(echo "$VLESS_URL" | grep -oP 'encryption=\K[^&]*')
SECURITY=$(echo "$VLESS_URL" | grep -oP 'security=\K[^&]*')
NETWORK=$(echo "$VLESS_URL" | grep -oP 'type=\K[^&]*')
SNI=$(echo "$VLESS_URL" | grep -oP 'sni=\K[^&]*')
FP=$(echo "$VLESS_URL" | grep -oP 'fp=\K[^&]*')
PBK=$(echo "$VLESS_URL" | grep -oP 'pbk=\K[^&]*')
PATH_PARAM=$(echo "$VLESS_URL" | grep -oP 'path=\K[^&]*')

CONFIG_PATH="config.json"
#CONFIG_PATH="/usr/local/etc/xray/config.json"

mkdir -p "$(dirname $CONFIG_PATH)"

cat > "$CONFIG_PATH" <<EOF
{
  "log": {
    "loglevel": "info"
  },
  "inbounds": [
    {
      "port": 1080,
      "listen": "0.0.0.0",
      "protocol": "socks",
      "settings": {
        "auth": "noauth",
        "udp": true
      },
      "sniffing": {
        "enabled": true,
        "destOverride": ["http", "tls"]
      }
    },
    {
      "port": 1081,
      "listen": "0.0.0.0",
      "protocol": "http",
      "settings": {}
    }
  ],
  "outbounds": [
    {
      "protocol": "vless",
      "settings": {
        "vnext": [
          {
            "address": "$ADDRESS",
            "port": $PORT,
            "users": [
              {
                "id": "$UUID",
                "encryption": "$ENCRYPTION"
              }
            ]
          }
        ]
      },
      "streamSettings": {
        "network": "$NETWORK",
        "security": "$SECURITY",
        "realitySettings": {
          "serverName": "$SNI",
          "fingerprint": "$FP",
          "publicKey": "$PBK",
          "shortId": "",
          "spiderX": ""
        },
        "xhttpSettings": {
          "path": "$PATH_PARAM",
          "host": "$SNI"
        }
      }
    },
    {
      "protocol": "freedom",
      "tag": "direct",
      "settings": {}
    }
  ],
  "routing": {
    "rules": [
      {
        "type": "field",
        "ip": ["geoip:private"],
        "outboundTag": "direct"
      }
    ]
  }
}
EOF

echo "配置文件已生成：$CONFIG_PATH"